<!-- 蓝色简洁登录页面 -->
<template>
  <view class="t-login">
    <!-- 页面装饰图片 -->
    <image class="img-a" src="https://zhoukaiwen.com/img/loginImg/2.png"></image>
    <image class="img-b" src="https://zhoukaiwen.com/img/loginImg/3.png"></image>
    <!-- 标题 -->
    <view class="t-b">{{ title }}</view>
    <view class="t-b2">欢迎使用，校园跑腿小程序</view>
    <form class="cl">
      <view class="t-a">
        <image src="https://zhoukaiwen.com/img/loginImg/sj.png"></image>
        <view class="line"></view>
        <input type="number" name="phone" placeholder="请输入手机号" maxlength="11" v-model="phone" />
      </view>
      <view class="t-a">
        <image src="https://zhoukaiwen.com/img/loginImg/yz.png"></image>
        <view class="line"></view>
        <input type="number" name="code" maxlength="6" placeholder="请输入验证码" v-model="yzm" />
        <view v-if="showText" class="t-c" @click="getCode()">发送短信</view>
        <view v-else class="t-c" style="background-color: #A7A7A7;">重新发送({{ second }})</view>
      </view>
      <button class="bg-blue" @click="login()">登 录</button>
      <button class="bg-green" @click="goAuthentication()">认证跑腿骑手</button>
    </form>
    <view class="t-f"><text>————— 快捷一键登录 —————</text></view>
    <view class="t-e cl">
      <view class="t-g" @tap="getUserInfo()">
        <image src="https://zhoukaiwen.com/img/loginImg/wx.png"></image>
      </view>
<!--      <view class="t-g" @tap="zfbLogin()">
        <image src="https://zhoukaiwen.com/img/loginImg/qq.png"></image>
      </view> -->
    </view>
  </view>
</template>
<script>
  import {
    mapMutations,
    mapState,
    mapActions
  } from 'vuex'
  export default {
    data() {
      return {
        title: '校园跑腿！', //填写logo或者app名称，也可以用：欢迎回来，看您需求
        second: 60, //默认60秒
        showText: true, //判断短信是否发送
        phone: '', //手机号码
        yzm: '', //验证码
        smsYzm: ''
      };
    },
    onLoad() {},
    mounted() {

    },
    computed: {
      ...mapState('m_user', ['redirectInfo'])
    },
    methods: {
      ...mapMutations('m_user', ['updateUserInfo', 'updateToken', 'updateRedirectInfo']),
      ...mapActions('m_user', ['hasItBeenRegistered']),
      //当前登录按钮操作
      async login() {
        var that = this;
        if (!that.phone) {
          uni.showToast({
            title: '请输入手机号',
            icon: 'none'
          });
          return;
        }
        if (!/^[1][3,4,5,7,8,9][0-9]{9}$/.test(that.phone)) {
          uni.showToast({
            title: '请输入正确手机号',
            icon: 'none'
          });
          return;
        }
        if (!that.yzm) {
          uni.showToast({
            title: '请输入验证码',
            icon: 'none'
          });
          return;
        }

        if (that.yzm === that.smsYzm) {
          //检查用户是否已经注册
          that.hasItBeenRegistered(that.phone)
          uni.showToast({
            title: '登录成功！',
            icon: 'none'
          });
          this.getToken()
        } else {
          uni.showToast({
            title: '验证码错误！',
            icon: 'none'
          });
        }
      },
      //获取短信验证码
      getCode() {
        var that = this;
        if (!that.phone) {
          uni.showToast({
            title: '请输入手机号',
            icon: 'none'
          });
          return;
        }
        if (!/^[1][3,4,5,7,8,9][0-9]{9}$/.test(that.phone)) {
          uni.showToast({
            title: '请输入正确手机号',
            icon: 'none'
          });
          return;
        }
        var interval = setInterval(() => {
          that.showText = false;
          var times = that.second - 1;
          that.second = times < 10 ? '0' + times : times; //小于10秒补 0
          that.second = times;
          // console.log(times);
        }, 1000);
        setTimeout(() => {
          clearInterval(interval);
          that.second = 60;
          that.showText = true;
        }, 60000);
        //这里请求后台获取短信验证码
        uniCloud.callFunction({
          name: 'sms-verification',
          data: {
            phone: that.phone
          }
        }).then((res) => {
          console.log(res.result)
          that.smsYzm = res.result.code
        }).catch((err) => {
          console.error(err)
        })

      },
      //等三方微信登录
      getUserInfo() {
        // 判断是否获取用户信息成功
        uni.getUserProfile({
          desc: '登录', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
          success: async (res) => {
            const db = uniCloud.database();
            const {
              result: getUserInfo
            } = await db.collection("my_user").get();
            const result = getUserInfo.data.find(item => {
              return item.user_name == res.userInfo.nickName;
            })
            console.log(result);
            // 判断用户名是否存在 新用户 新增
            if (result === undefined) {
              const myUser = {
                user_name: res.userInfo.nickName,
                avatarUrl: res.userInfo.avatarUrl
              }
              await db.collection("my_user").add(myUser)
              //用户不存在 获取新增的数据持久化存储本地
              const {
                result: newUserInfo
              } = await db.collection("my_user").where({
                user_name: myUser.user_name
              }).get();
              console.log(newUserInfo.data[0]);
              this.updateUserInfo(newUserInfo.data[0]);
            } else {
              //用户存在 将获取数据持久化存储本地
              this.updateUserInfo(result);
            }
            this.getToken()
          },
          fail: (res) => {
            return uni.$showMsg('您取消了登录授权！')
          }
        });
      },
      async getToken() {
        //获取code对应的值
        const res = await uni.login().catch(err => err);
        // console.log(res);
        if (res.errMsg !== 'login:ok') return uni.$showMsg('登录失败！')

        //自定义一个随机token
        const newtoken = this.generateToken();
        this.updateToken(newtoken)
        uni.navigateTo({
          url: '/pages/index/index'
        })
      },
      //生成随机token
      generateToken() {
        let token = '';
        const tokenLength = 32;
        const possibleChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        for (let i = 0; i < tokenLength; i++) {
          token += possibleChars.charAt(Math.floor(Math.random() * possibleChars.length));
        }
        return 'Bearer ' + token;
      },
      //去认证
      goAuthentication() {
        uni.navigateTo({
          url: '/subpkg-runner/runner-login/runner-login'
        })
      }

    }
  };
</script>
<style lang="scss">
  .img-a {
    position: absolute;
    width: 100%;
    top: -150rpx;
    right: 0;
  }

  .img-b {
    position: absolute;
    width: 50%;
    bottom: 0;
    left: -50rpx;
    /* margin-bottom: -200rpx; */
  }

  .t-login {
    width: 650rpx;
    margin: 0 auto;
    font-size: 28rpx;
    color: #000;
  }

  .t-login button {
    font-size: 28rpx;
    color: #fff;
    height: 90rpx;
    line-height: 90rpx;
    border-radius: 50rpx;
    box-shadow: 0 5px 7px 0 rgba(86, 119, 252, 0.2);
    margin: 20px 0;
  }

  .t-login input {
    padding: 0 180rpx 0 120rpx;
    height: 90rpx;
    line-height: 90rpx;
    margin-bottom: 50rpx;
    background: #f8f7fc;
    border: 1px solid #e9e9e9;
    font-size: 28rpx;
    border-radius: 50rpx;
  }

  .t-login .t-a {
    position: relative;
  }

  .t-login .t-a image {
    width: 40rpx;
    height: 40rpx;
    position: absolute;
    left: 40rpx;
    top: 28rpx;
    /* border-right: 2rpx solid #dedede; */
    margin-right: 20rpx;
  }

  .t-login .t-a .line {
    width: 2rpx;
    height: 40rpx;
    background-color: #dedede;
    position: absolute;
    top: 28rpx;
    left: 98rpx;
  }

  .t-login .t-b {
    text-align: left;
    font-size: 46rpx;
    color: #000;
    padding: 300rpx 0 30rpx 0;
    font-weight: bold;
  }

  .t-login .t-b2 {
    text-align: left;
    font-size: 32rpx;
    color: #aaaaaa;
    padding: 0rpx 0 120rpx 0;
  }

  .t-login .t-c {
    position: absolute;
    right: 22rpx;
    top: 22rpx;
    background-color: #0081ff;
    color: #fff;
    font-size: 24rpx;
    border-radius: 50rpx;
    height: 50rpx;
    line-height: 50rpx;
    padding: 0 25rpx;

  }

  .t-login .t-d {
    text-align: center;
    color: #999;
    margin: 80rpx 0;
  }

  .t-login .t-e {
    text-align: center;
    width: 100%;
    margin: 80rpx auto 0;
  }

  .t-login .t-g {
    // float: left;
    // width: 50%;
  }

  .t-login .t-e image {
    width: 50rpx;
    height: 50rpx;
  }

  .t-login .t-f {
    text-align: center;
    margin: 200rpx 0 0 0;
    color: #666;
  }

  .t-login .t-f text {
    margin-left: 20rpx;
    color: #aaaaaa;
    font-size: 27rpx;
  }

  .t-login .uni-input-placeholder {
    color: #000;
  }

  .cl {
    zoom: 1;
  }

  .cl:after {
    clear: both;
    display: block;
    visibility: hidden;
    height: 0;
    content: '\20';
  }
</style>